package com.xjj.link;

public class H0025ReverseNodesInKGroup {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode protectNode = new ListNode(0, head);
        ListNode last = protectNode;
        while (head != null) {
            // 分组
            ListNode groupTail = getTail(head, k);
            if (groupTail == null) {
                break;
            }

            // 组内反转
            reverseList(head, groupTail);

            // 组尾(head)连下组原尾
            // 没必要去预先求下组数据,所以可以转换成上组尾(添加保护节点)连本组头(原尾)
            last.next = groupTail;

            last = head;
            // 交换时把原组头指向了下组头,所以直接下移就行
            head = head.next;
        }
        return protectNode.next;
    }

    private ListNode getTail(ListNode head, int k) {
        while (head != null) {
            if (--k == 0) {
                break;
            }
            head = head.next;
        }
        return head;
    }

    private void reverseList(ListNode head, ListNode tail) {
        // 先连一下下组头,不用去处理最后组特殊情况
        ListNode last = tail.next;
        // 判断不是同一对象,直接用等于
        while (head != tail) {
            ListNode beforeNext = head.next;
            head.next = last;
            last = head;
            head = beforeNext;
        }
        // 跳出时还差部反转
        tail.next = last;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
